import { Upload, message } from 'antd'
import { InboxOutlined } from '@ant-design/icons'
import { useState } from 'react'
import { commonApi } from '@/services/api'

const { Dragger } = Upload

export default function UploadFile({
    accept,
    maxSize = 10, // MB
    maxCount = 1,
    onChange,
    ...props
}) {
    const [loading, setLoading] = useState(false)

    const handleUpload = async options => {
        const { file, onSuccess, onError } = options

        if (file.size / 1024 / 1024 > maxSize) {
            message.error(`文件大小不能超过 ${maxSize}MB`)
            return
        }

        try {
            setLoading(true)
            const response = await commonApi.upload(file)
            onSuccess(response, file)
            onChange?.(response.url)
            message.success('上传成功')
        } catch (error) {
            onError(error)
            message.error('上传失败')
        } finally {
            setLoading(false)
        }
    }

    return (
        <Dragger
            name="file"
            multiple={false}
            maxCount={maxCount}
            accept={accept}
            customRequest={handleUpload}
            loading={loading}
            {...props}
        >
            <p className="ant-upload-drag-icon">
                <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p className="ant-upload-hint">
                支持单个或批量上传，文件大小不超过 {maxSize}MB
            </p>
        </Dragger>
    )
} 